<template>
  <div>
    <div class="top">
      <div class="search">
        <el-form :inline="true" :model="formInline">
          <el-form-item :label="t('productId')" class="status">
            <el-select
              v-model="formInline.product_id"
              :placeholder="t('pleaseSelect')"
              clearable
            >
              <el-option
                v-for="product in productList"
                :key="product.product_id"
                :label="product.product_name"
                :value="product.product_id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery()">{{ t('query') }}</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addProduct()"
            >{{ t('addRepayScheme') }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-table class="table_content" :data="configList" :border="true" v-loading="loading">
      <el-table-column prop="product_id" :label="t('productId')"></el-table-column>
      <el-table-column prop="amount_max" :label="t('maxAmount')"></el-table-column>
      <el-table-column prop="amount_min" :label="t('minAmount')"></el-table-column>
      <el-table-column prop="amount_step" :label="t('step')"></el-table-column>
      <el-table-column prop="term" :label="t('period')"></el-table-column>
      <el-table-column prop="total_period" :label="t('totalPeriod')"></el-table-column>
      <el-table-column prop="config_status" :label="t('status')">
        <template #default="{ row }">
          <el-tag v-if="row.config_status === 1" type="success">{{ t('hasOpen') }}</el-tag>
          <el-tag v-else type="danger">{{ t('hasClose') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="update_time"
        :label="t('updateTime')"
      ></el-table-column>
      <el-table-column :label="t('op')">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleView(row)"
          >{{ t('view') }}
          </el-button
          >
          <el-button type="danger" size="small" @click="handleEnable(row,0)"
                     v-if="row.config_status === 1">{{ t('close') }}
          </el-button>
          <el-button type="warning" size="small" @click="handleEnable(row,1)" v-else>{{ t('open') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="state.total"
    >
    </el-pagination>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, toRefs, onMounted, watchEffect, watch } from 'vue'
import {
  ElTable,
  ElTableColumn,
  ElPagination,
  ElTag,
  ElButton, ElMessage
} from 'element-plus'
import { useRouter } from 'vue-router'
import useRepaySchemeStore from '@/stores/repaySchemeStore'
import { getRepaySchemeListById, updateConfigStatus } from '@/api/repayScheme'
import { storeToRefs } from 'pinia'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const repaySchemeStore = useRepaySchemeStore()
const router = useRouter()

let loading = ref(false)
const configList = ref([])
const state = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

function loadData() {
  if (!formInline.product_id) {
    return
  }
  loading.value = true
  getRepaySchemeListById(formInline.product_id, state.value.currentPage, state.value.pageSize)
    .then((res) => {
      configList.value = res.config_list
      state.value.total = res.total
    })
    .catch((err) => {
      console.log('err:', err)
    }).finally(() => {
    loading.value = false
  })
}

onMounted(() => {
  repaySchemeStore.getProductList()
  loadData()
})

const { productList } = storeToRefs(repaySchemeStore)

const formInline = reactive({
  product_id: null
})

const handleQuery = () => {
  loadData()
}

watch(() => productList.value, (newProductList, oldProductList) => {
  // 這裡的代碼只會在 productList.value 發生變化時執行
  if (newProductList.length > 0) {
    formInline.product_id = newProductList[0].product_id
    loadData()
  }
}, { immediate: true })


const addProduct = () => {
  router.push({ name: 'newScheme' })
}

const handleView = (row: any) => {
// 处理查看逻辑
  router.push({
    name: 'newScheme', query: {
      item: JSON.stringify(row)
    }
  })
}

const handleEnable = (row: any, status: number) => {
  loading.value = true
  updateConfigStatus(row.id, status)
    .then(() => {
      ElMessage.success(t('updateSuccess'))
      loadData()
    })
    .catch((err) => {
      console.log('err:', err)
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSizeChange = (newSize: any) => {
  state.value.pageSize = newSize
}

const handleCurrentChange = (newPage: any) => {
  state.value.currentPage = newPage
  loadData()
}

// 导出响应式状态的引用
const { currentPage, pageSize } = toRefs(state.value)
</script>

<style scoped lang="scss">
.top {
  width: 98%;
  margin-top: 28px;
  margin-bottom: 10px;

  .add {
    float: right;
  }

  .status {
    width: 180px;
  }
}

.table_content {
  width: 98%;
  margin-top: 20px;
}
</style>
